package kr.co.bettersoft.usedmarketandroid.fragment;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import kr.co.bettersoft.usedmarketandroid.activity.R;
import kr.co.bettersoft.usedmarketandroid.activity.UsedMarketCertificationActivity;
import kr.co.bettersoft.usedmarketandroid.activity.UsedMarketRecommandToFriendsActivity;
import kr.co.bettersoft.usedmarketandroid.activity.UsedMarketRetireActivity;
import kr.co.bettersoft.usedmarketandroid.activity.UsedMarketWebViewActivity;
import kr.co.bettersoft.usedmarketandroid.activity.UsedMarketWhatIsThisActivity;
import kr.co.bettersoft.usedmarketandroid.activity.UsedMarketCertificationActivity.backgroundThreadCertificationStep1;
import kr.co.bettersoft.usedmarketandroid.common.CommonConstant;
import kr.co.bettersoft.usedmarketandroid.common.UsedMarketRest;
import kr.co.bettersoft.usedmarketandroid.domain.UsedMarketMember;
import kr.co.bettersoft.usedmarketandroid.domain.UsedMarketSMS;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ToggleButton;


import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageButton;
import android.widget.TextView;

/**
 * 
 * 설정.
 *  사용자 정보
 *    멤버 등록
 *    푸쉬 알림 설정 [on/off] 슬라이드 버튼 이용 - 별도 액티비티 x.  기본 값은 true
 *    친구에게 추천하기	: 친구목록, 왼쪽 체크박스 체크 후 보내기 버튼으로 일괄 전송
 *  기본 정보
 *    이용약관		: 웹뷰
 *    공지사항		: 웹뷰
 *    자주묻는질문		: 웹뷰
 *    What is this?	: 뷰. 터치시 종료
 * 
 * @author blue
 *
 */
public class FragmentMenu5Settings extends Fragment{			
	//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	// 변수

	String TAG = "FragmentMenu5Settings";

//	public final int DEACTIVATE_USER = 101; // 멤버 탈퇴하기
	
	// 메뉴.
	View certiLayout;
	View pushOnOffLayout;
	View recommandToFriendsLayout;
	View retireLayout;
	
	View termsLayout;
	View privacyLayout;
	View youthLayout;
//	View noticeLayout;
//	View qnaLayout;
	View whatIsThisLayout;

	
	String phoneNum = "";
	// 설정 파일 저장소  
	SharedPreferences sharedPrefCustom;
	
	
	ToggleButton toggleButtonPushReceiveOnOff;
	boolean  pushOn;
	
	ProgressBar pb1;		// 중단 로딩 진행바
	
	//	/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	
	// 핸들러
	Handler handler = new Handler(){
		@Override
		public void handleMessage(Message msg){
			Bundle b = msg.getData();
			try{
				if(b.getInt("showErrToast")==1){
					Toast.makeText(returnThis(), b.getString("msg"), Toast.LENGTH_SHORT).show();
				}
				if(b.getInt("showAlert")==1){					 // 알림 및 경고창 . 
					new AlertDialog.Builder(returnThis())
					.setTitle(CommonConstant.alertTitle)							
					.setMessage(b.getString("msg"))
					.setIcon(R.drawable.ic_launcher)		// 경고창.  
					.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int whichButton) {
							// 그냥 사용자 확인 용이기 때문에 추가 조작 없음.
						}})
						.setNegativeButton("", null).show();
				}		 
//				if(b.getInt("confirmRetire")==1){		
//					new AlertDialog.Builder(returnThis())
//					.setTitle(CommonConstant.alertTitle)							
//					.setMessage("탈퇴하시겠습니까?")
//					.setIcon(R.drawable.ic_launcher)		// 경고창.  
//					.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
//						public void onClick(DialogInterface dialog, int whichButton) {
//							// 탈퇴 진행
//							Log.d(TAG,"retire..");
//							handler.sendEmptyMessage(DEACTIVATE_USER);
//						}})
//						.setNegativeButton(android.R.string.no, null)		 
//						.show();	// 탈퇴 취소
//				}
				if(b.getInt("order")==1){
					// 프로그래스바 실행
					pb1.setVisibility(View.VISIBLE);
				}else if(b.getInt("order")==2){
					// 프로그래스바  종료
					pb1.setVisibility(View.INVISIBLE);
				}
				
//				switch (msg.what)
//				{
//					case DEACTIVATE_USER : getActivity().runOnUiThread(new RunnableUpdateDeactivate());				
//						break;
//					case CERTIFICATION_STEP2 : runOnUiThread(new RunnableCertificationStep2());
//						break;
//					default : 
//						break;
//				}

				
			}catch(Exception e){
				e.printStackTrace();
			}
		}
	};
	
	
	
	//	/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	//		
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
	{
		View view = inflater.inflate(R.layout.fragment_menu5_settings, null);

		// prefs
		sharedPrefCustom = getActivity().getSharedPreferences(CommonConstant.prefName,
				Context.MODE_WORLD_READABLE | Context.MODE_WORLD_WRITEABLE);
		phoneNum = sharedPrefCustom.getString("phoneNum", "");
		
		pushOn = sharedPrefCustom.getBoolean("pushOn", true);
		
		pb1=(ProgressBar) view.findViewById(R.id.progressbar);	
		
		
		// 메뉴 항목들
		certiLayout = view.findViewById(R.id.certi_layout);
		pushOnOffLayout = view.findViewById(R.id.push_on_off_layout);
		recommandToFriendsLayout = view.findViewById(R.id.recommand_to_friends_layout);
		retireLayout = view.findViewById(R.id.retire_layout);
		
		termsLayout = view.findViewById(R.id.terms_layout);
		
		privacyLayout = view.findViewById(R.id.privacy_layout);
		youthLayout = view.findViewById(R.id.youth_layout);
//		noticeLayout = view.findViewById(R.id.notice_layout);
//		qnaLayout = view.findViewById(R.id.qna_layout);
		whatIsThisLayout = view.findViewById(R.id.what_is_this_layout);
		
		// 메뉴 항목들에 대한 리스너
		certiLayout.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Log.d(TAG,"certiLayout onClick");
				Intent intent = new Intent(returnThis(), UsedMarketCertificationActivity.class);
				startActivity(intent);
			}
		});
		pushOnOffLayout.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Log.d(TAG,"pushOnOffLayout onClick");
//				Intent intent = new Intent(returnThis(), UsedMarketCertificationActivity.class);
//				startActivity(intent);
			}
		});
		recommandToFriendsLayout.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Log.d(TAG,"recommandToFriendsLayout onClick");
				Intent intent = new Intent(returnThis(), UsedMarketRecommandToFriendsActivity.class);
				startActivity(intent);
			}
		});
		retireLayout.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Log.d(TAG,"retireLayout onClick");
				
				phoneNum = sharedPrefCustom.getString("phoneNum", "");
				if(phoneNum.length()<1){
					alert("등록된 멤버 정보가 없습니다.");
				}else{
					Intent intent = new Intent(returnThis(), UsedMarketRetireActivity.class);
					startActivity(intent);
//					confirmRetire();		// ### 
				}
			}
		});
		
		termsLayout.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Log.d(TAG,"termsLayout onClick");			// loadingURL
				Intent intent = new Intent(returnThis(), UsedMarketWebViewActivity.class);
				intent.putExtra("loadingURL", CommonConstant.termsPolicyURL);
				intent.putExtra("isGetRequest", true);
				startActivity(intent);
			}
		});

		privacyLayout.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Log.d(TAG,"noticeLayout onClick");
				Intent intent = new Intent(returnThis(), UsedMarketWebViewActivity.class);
				intent.putExtra("loadingURL", CommonConstant.privacyPolicyURL);
				intent.putExtra("isGetRequest", true);
				startActivity(intent);
			}
		});
		
		youthLayout.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Log.d(TAG,"noticeLayout onClick");
				Intent intent = new Intent(returnThis(), UsedMarketWebViewActivity.class);
				intent.putExtra("loadingURL", CommonConstant.youthPolicyURL);
				intent.putExtra("isGetRequest", true);
				startActivity(intent);
			}
		});
		
//		noticeLayout.setOnClickListener(new OnClickListener() {
//			@Override
//			public void onClick(View v) {
//				Log.d(TAG,"noticeLayout onClick");
//				Intent intent = new Intent(returnThis(), UsedMarketWebViewActivity.class);
//				intent.putExtra("loadingURL", CommonConstant.noticeURL);
//				intent.putExtra("isGetRequest", true);
//				startActivity(intent);
//			}
//		});
//		qnaLayout.setOnClickListener(new OnClickListener() {
//			@Override
//			public void onClick(View v) {
//				Log.d(TAG,"qnaLayout onClick");
//				Intent intent = new Intent(returnThis(), UsedMarketWebViewActivity.class);
//				intent.putExtra("loadingURL", CommonConstant.qnaURL);
//				intent.putExtra("isGetRequest", true);
//				startActivity(intent);
//			}
//		});
		whatIsThisLayout.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Log.d(TAG,"whatIsThisLayout onClick");
				Intent intent = new Intent(returnThis(), UsedMarketWhatIsThisActivity.class);
				startActivity(intent);
			}
		});
		
		
		
		
		
		
		// 메시지 알림 설정 on/off
		toggleButtonPushReceiveOnOff = (ToggleButton) view.findViewById(R.id.toggleButtonPushReceiveOnOff);
		// 메시지 수신 알림 설정
		if(pushOn){
			toggleButtonPushReceiveOnOff.setChecked(true);
		}else{
			toggleButtonPushReceiveOnOff.setChecked(false);
		}
		// 리스너
		toggleButtonPushReceiveOnOff.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				// TODO Auto-generated method stub
				showPb();
				if(isChecked){
					Log.d(TAG,"toggleButtonPushReceiveOnOff isChecked:"+isChecked);
				}else{
					Log.d(TAG,"toggleButtonPushReceiveOnOff isChecked:"+isChecked);
				}
				pushOn = isChecked;
				
				// 저장
				SharedPreferences sharedPreferences = returnThis().getSharedPreferences(CommonConstant.prefName, Activity.MODE_PRIVATE);
				SharedPreferences.Editor editor = sharedPreferences.edit();
				editor.putBoolean("pushOn", pushOn);		 
				editor.commit();
				hidePb();
			}
		});
		
		
		
		
		
		
		
		return view;
	}
	
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	// 서버 통신
	
//	/**
//	 * 러너블. 멤버 탈퇴  updateDeactivate
//	 */
//	class RunnableUpdateDeactivate implements Runnable {
//		public void run(){
//			new backgroundThreadUpdateDeactivate().execute();
//		}
//	}
//	/**
//	 * backgroundThreadUpdateDeactivate
//	 * 비동기    서버와 통신하여 서버와 통신하여 멤버 탈퇴 
//	 * @author blue
//	 *
//	 */
//	public class backgroundThreadUpdateDeactivate extends AsyncTask<Void, Void, Void>{
//		@Override protected void onPostExecute(Void result) {  
//		} 
//		@Override protected void onPreExecute() {  
//		} 
//		@Override protected Void doInBackground(Void... params) {  
//			Log.d(TAG,"backgroundThreadUpdateDeactivate");
//			
//			// 파라미터 세팅
//			
//			UsedMarketMember usedMarketMember = new UsedMarketMember();
//			usedMarketMember.setPhoneNumber(phoneNum);
//			
//			// 서버 메소드 호출
//			showPb();
//			UsedMarketRest usedMarketRest = new UsedMarketRest();
//			String result = usedMarketRest.RestUpdateDeactivate(usedMarketMember);
//			Log.d(TAG,"backgroundThreadUpdateDeactivate result::"+result);
//			if(result.equals("SUCCESS")){
//				// 탈퇴 성공.
//				
//				// 멤버 정보 삭제 
//				SharedPreferences sharedPreferences = getActivity().getSharedPreferences(CommonConstant.prefName, Activity.MODE_PRIVATE);
//				SharedPreferences.Editor editor = sharedPreferences.edit();
//				phoneNum = "";
//				editor.putString("agreedYN", "N");			// 인증 여부 저장
//				editor.putString("phoneNum", "");		// 전번도 저장	 
//				editor.commit();
//				
//				alert("탈퇴 되었습니다.");	
//			}else{
//				// 인증 실패.
//				alert("요청이 실패하였습니다.");
//			}
//			hidePb();
//			return null; 
//		}
//	}
	
	
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////	
	public Context returnThis(){
		return getActivity();
	}

	
	/**
	 * alert
	 * 얼럿 창 띄우기
	 *
	 * @param msg
	 * @param 
	 * @return 
	 */
	public void alert(final String msg){
		getActivity().runOnUiThread(new Runnable(){
			public void run(){
				Message message = handler.obtainMessage();				
				Bundle b = new Bundle();
				b.putInt("showAlert", 1);
				b.putString("msg", msg);			// 화면에 보여줄 메시지
				message.setData(b);
				handler.sendMessage(message);
			}
		});
	}
	
//	/**
//	 * confirmRetire
//	 * 얼럿 창 띄우기
//	 *
//	 * @param msg
//	 * @param 
//	 * @return 
//	 */
//	public void confirmRetire(){
//		getActivity().runOnUiThread(new Runnable(){
//			public void run(){
//				Message message = handler.obtainMessage();				
//				Bundle b = new Bundle();
//				b.putInt("confirmRetire", 1);
//				message.setData(b);
//				handler.sendMessage(message);	
//			}
//		});
//	}
	
	
	// 중앙 프로그래스바 보임, 숨김
	/**
	 * showPb
	 *  중앙 프로그래스바 가시화한다
	 *
	 * @param
	 * @param
	 * @return
	 */
	public void showPb(){
		if(getActivity()!=null){
			getActivity().runOnUiThread(new Runnable(){		 
				@Override
				public void run(){
					Message message = handler .obtainMessage();
					Bundle b = new Bundle();
					b.putInt( "order" , 1);
					message.setData(b);
					handler .sendMessage(message);
				}
			});
		}
		
	}
	/**
	 * hidePb
	 *  중앙 프로그래스바 비가시화한다
	 *
	 * @param
	 * @param
	 * @return
	 */
	public void hidePb(){
		if(getActivity()!=null){
			getActivity().runOnUiThread(new Runnable(){		 
				@Override
				public void run(){
					Message message = handler .obtainMessage();
					Bundle b = new Bundle();
					b.putInt( "order" , 2);
					message.setData(b);
					handler .sendMessage(message);
				}
			});
		}
		
	}
	
	
	
}